const util = require('../../../../../../utils/util.js');
const api = require('../../../../../../config/api.js');
const user = require('../../../../../../services/user.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //选择的面板
    panel: 1,
    //契约金开始时间
    startDate: '',
    //契约金结束时间
    endDate: '',
    //契约金最低开始时间
    minStartDate: '',
    //契约金最低结束结束时间
    minEndDate: '',
    //周期天数
    dateSum: '',
    //目标周期
    sumDay: [],
    //圈子ID
    circleid: '',
    //全部契约
    contractAll: [
      {
        //展示开始日期
        validityStartValue: '',
        //展示结束日期
        validityEndValue: '',
        //带年份开始日期
        validityStart: '',
        //带年份结束日期
        validityEnd: '',
        //参加人数
        participants: 0,
        //奖金池
        bonus: '0',
        //最少打卡多少天
        daysRemaining: 0
      }
    ],
  },
  //页面加载
  onLoad: function (options) {
    var _this = this
    _this.setData({
      circleid: options.circleid
    })
    //初始时间
    var date = new Date();
    var start = util.getDateStr(date, 1);
    var end = util.getDateStr(date, 2);
    var day = (new Date(end).getTime() - new Date(start).getTime()) / (1000 * 60 * 60 * 24) + 1;
    _this.setData({
      viewStart: start.substring(5),
      viewEnd: end.substring(5),
      minStartDate: start,
      minEndDate: end,
      startDate: start,
      endDate: end,
      dateSum: day
    })
    _this.countDay();
  },
  //获取契约
  onShow: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var param = {};
        param.access_token = res.access_token;
        param.circleid = _this.data.circleid;
        util.post(api.Interest_getContractAll, param).then(function (res2) {
          if (res2.code == 200) {
            if (null != res2.result.obj && res2.result.obj.length > 0) {
              var date = new Date();
              var newD = util.getDateStr(date, 0);
              for (var i = 0; i < res2.result.obj.length; i++) {
                console.log(new Date(res2.result.obj[i].validityStart.replace(/-/g, '/')).getTime())
                if (new Date(newD.replace(/-/g, '/')).getTime() < new Date(res2.result.obj[i].validityStart.replace(/-/g, '/')).getTime()) {
                  res2.result.obj[i].state = "#f47171" 
                } else if (new Date(newD.replace(/-/g, '/')).getTime() < new Date(res2.result.obj[i].validityEnd.replace(/-/g, '/')).getTime()) {
          res2.result.obj[i].state = "#baf0b3" 
                } else if (new Date(newD.replace(/-/g, '/')).getTime() - new Date(res2.result.obj[i].validityEnd.replace(/-/g, '/')).getTime() >= 86400000) {
                  res2.result.obj[i].state = "#f4c363"
                } else {
                  res2.result.obj[i].state = "#7ec1f4"
                }
                res2.result.obj[i].viewValidityStart = res2.result.obj[i].validityStart.substring(0,10)
                res2.result.obj[i].viewValidityEnd = res2.result.obj[i].validityEnd.substring(0,10)
              }
              _this.setData({
                contractAll: res2.result.obj,
                panel: 2
              })
              console.log(_this.data.contractAll)
            }
          }
        })
      })
    }
  },
  //选择开始时间
  bindDateChangeStart: function (e) {
    var _this = this
    var date = e.detail.value
    var end = _this.data.endDate
    var minEnd = util.getDateStr(date, 1);
    var day = (new Date(end).getTime() - new Date(date).getTime()) / (1000 * 60 * 60 * 24) + 1;
    if (day <= 0) {
      var newDay = (new Date(minEnd).getTime() - new Date(date).getTime()) / (1000 * 60 * 60 * 24) + 1;
      _this.setData({
        viewStart: date.substring(5),
        viewEnd: minEnd.substring(5),
        startDate: date,
        endDate: minEnd,
        minEndDate: minEnd,
        dateSum: newDay
      })
    } else {
      _this.setData({
        viewStart: date.substring(5),
        startDate: date,
        minEndDate: minEnd,
        dateSum: day
      })
    }
    _this.countDay();
  },
  //选择结束时间
  bindDateChangeEnd: function (e) {
    var _this = this
    var date = e.detail.value
    var start = _this.data.startDate
    var day = (new Date(date).getTime() - new Date(start).getTime()) / (1000 * 60 * 60 * 24) + 1;
    _this.setData({
      viewEnd: date.substring(5),
      endDate: date,
      dateSum: day
    })
    _this.countDay();
  },
  //选择周期天数
  bindPickerChange: function (e) {
    var _this = this
    var index = e.detail.value
    var arr = _this.data.sumDay
    var selectDay = arr[index].name
    var selectDaySum = arr[index].id
    _this.setData({
      selectDay: selectDay,
      selectDaySum: selectDaySum
    })
  },
  //获取输入金额
  changeDeedMoney: function (e) {
    var _this = this
    var money = e.detail.value
    _this.setData({
      deedMoney: money
    })
  },
  //立即创建契约金
  gocontractdetails: function () {
    var _this = this;
    var startDate = _this.data.startDate
    var endDate = _this.data.endDate
    var selectDaySum = _this.data.selectDaySum
    var deedMoney = _this.data.deedMoney
    if (startDate != '' && startDate != null && endDate != '' && endDate != null && selectDaySum != '' && selectDaySum != null && deedMoney != '' && deedMoney != null) {
      let param = {};
      var openid = app.globalData.logininfo.openid;
      if (openid != null && openid != "") {
        util.post(api.fetchToken()).then(function (res) {
          if (res.access_token != '') {
            return Promise.resolve({
              access_token: res.access_token
            });
          }
        }).then(function (res) {
          let url = api.Interest_insertContract;
          param.access_token = res.access_token;
          param.circleid = _this.data.circleid;
          param.validityStart = startDate;
          param.validityEnd = endDate;
          param.targetdate = selectDaySum;
          param.price = deedMoney;
          util.post(url, param).then(function (res2) {
            if (res2.code == 200) {
              wx.showToast({
                title: '创建成功',
                icon: 'none',
                duration: 2000
              })
              var id = res2.result
              wx.navigateTo({
                url: '../createcontract/contractdetails/contractdetails?id=' + id
              })
            }
          })
        })
      }
    } else {
      wx.showToast({
        title: '请先填写完整',
        icon: 'none',
        duration: 2000
      })
    }
  },
  //进入详情页面
  gotoDetails: function (e) {
    var id = e.currentTarget.dataset.id
    console.log(id)
    wx.navigateTo({
      url: '../createcontract/contractdetails/contractdetails?id=' + id
    })
  },
  //计算周期天数
  countDay: function () {
    var _this = this
    var day = parseInt(_this.data.dateSum)
    var arr = [];
    for (var i = 1; i <= day; i++) {
      arr.push({ "id": i, "name": i + "天" })
    }
    _this.setData({
      sumDay: arr
    })
  },
  //切换面板
  switchPanel: function (e) {
    var _this = this
    var sel = e.currentTarget.dataset.id
    _this.setData({
      panel: sel
    })
  }
})